<template>
  <div class="data-edit">
    <el-form :model="formData" ref="formRef">
      <el-table ref="tableRef" :data="formData.tableData" height="228px" empty-text="请先绘制区域" @select="onSelectionChange" @select-all="onSelectionChange">
        <el-table-column type="selection" width="30"></el-table-column>
        <el-table-column prop="markTypeName" label="标绘类型" width="80"></el-table-column>
        <el-table-column prop="btmc" label="标题名称" width="180">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData[${$index}].btmc`">
              <el-input v-model="row.btmc" placeholder="请输入" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="fzmc" label="分组名称" width="180">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData[${$index}].fzmc`">
              <el-input v-model="row.fzmc" placeholder="请输入" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="bz" label="备注" width="180">
          <template #default="{ row, $index }">
            <el-form-item :prop="`tableData[${$index}].bz`">
              <el-input v-model="row.bz" placeholder="请输入" />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column fixed="right" label="操作" width="50">
          <template #default="{ row, $index }">
            <el-popconfirm title="确认删除吗？" :hide-after="0" @confirm="onDelete(row, $index)">
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column> -->
      </el-table>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, computed, nextTick, ref, useTemplateRef } from 'vue';
import { MAP_EDIT_EVENT } from '@/components/Map/config';
import { ElMessage } from 'element-plus';
import { eventBus } from '@/utils/eventBus';

const props = defineProps({
  mapRef: {
    type: Object,
    default: () => ({}),
  },
});

// https://minedata.cn/minemapapi/minemap-plugins/edit/edit-api.html
onMounted(async () => {
  await nextTick();
  const mapReadyData = await props.mapRef.onMapReady();
  localMapEditor = mapReadyData.mapEditor;
  console.log('数据编辑组件实例', localMapEditor);
  
  localMapEditor.addEventListener(MAP_EDIT_EVENT.CREATED, onMapEditCreate);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.SELECTED, onMapEditSelected);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.SELECTED_CANCEL, onMapEditCancel);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.EDIT, onMapEdit);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.EDIT_CANCEL, onMapEditCancel);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.UPDATE, onMapEditUpdate);
  localMapEditor.addEventListener(MAP_EDIT_EVENT.DELETE, onMapEditDelete);

  eventBus.on('DrawSelect:onBeginDraw', onBeginDraw);
  eventBus.on('StyleEdit:onSelectData', onSelectData);
  eventBus.on('StyleEdit:onCancelSelectedRows', onCancelSelectedRows);
  eventBus.on('StyleEdit:onGetSelectedRowIds:request', onGetSelectedRowIds);
})

onUnmounted(() => {
  eventBus.off('DrawSelect:onBeginDraw', onBeginDraw);
  eventBus.off('StyleEdit:onSelectData', onSelectData);
  eventBus.off('StyleEdit:onCancelSelectedRows', onCancelSelectedRows);
  eventBus.off('StyleEdit:onGetSelectedRowIds:request', onGetSelectedRowIds);
})

let localMapEditor = null;
let currDrawMarkTypeItem = null;
const tableRef = useTemplateRef('tableRef');
const formData = reactive({ tableData: [] })

// 绘制开始时，地图默认会取消选中，这里更新表格的选中状态
const onBeginDraw = markTypeItem => {
  if (!tableRef.value) return;
  tableRef.value.clearSelection(); // 对应的getSelectionRows
  currDrawMarkTypeItem = markTypeItem;
}

const onSelectData = currMarkType => {
  if (!tableRef.value) return;
  tableRef.value.clearSelection();
  onSelectionChange([]);
  const selectList = [];
  formData.tableData.forEach(item => {
    if (item.markType == currMarkType) {
      tableRef.value.toggleRowSelection(item, true);
      selectList.push(item);
    }
  })
  onSelectionChange(selectList);
}

const onCancelSelectedRows = () => {
  if (!tableRef.value) return;
  tableRef.value.clearSelection();
  onSelectionChange([]);
}

const onGetSelectedRowIds = () => {
  if (!tableRef.value) return;
  eventBus.emit('DataEdit:onGetSelectedRowIds:response', tableRef.value.getSelectionRows().map(item => item.id))
}

const onMapEditCreate = async ({ data }) => {
  console.log('onMapEditCreate', data);
  const featureItem = data.features[0];
  const temp = { id: featureItem.id, jwd: featureItem, markType: currDrawMarkTypeItem.bh, markTypeName: currDrawMarkTypeItem.mc };
  formData.tableData = [temp, ...formData.tableData];
  currDrawMarkTypeItem = null;
  await nextTick();
  tableRef.value.toggleRowSelection(temp, true);
}

const onMapEditSelected = ({ data }) => {
  console.log('onMapEditSelected');
  data.featureIds.forEach(id => {
    tableRef.value.toggleRowSelection(formData.tableData.find(item => item.id === id), true);
  })
}

const onMapEditCancel = ({ data }) => {
  console.log('onMapEditCancel');
  data.featureIds.forEach(id => {
    tableRef.value.toggleRowSelection(formData.tableData.find(item => item.id === id), false);
  })
}

const onMapEdit = ({ data }) => {
  console.log('数据编辑组件 onMapEdit', data);
}

const onMapEditUpdate = ({ data }) => {
  console.log('数据编辑组件 onMapEditUpdate', data);
}

const onMapEditDelete = ({ data }) => {
  console.log('onMapEditDelete');
  formData.tableData = formData.tableData.filter(item => !data.featureIds.includes(item.id));
}

const onSelectionChange = (selectedRows) => {
  console.log('table onSelectionChange', selectedRows);
  localMapEditor.setSelected(selectedRows.map(item => item.id))
}

const onDelete = (row, index) => {
  formData.tableData.splice(index, 1);
  localMapEditor.draw.delete([row.id]);
}

const saveData = () => {
  if (!formData.tableData.length) return ElMessage.warning('请先绘制区域');
  console.log('tableData', formData.tableData);
}

defineExpose({ saveData, onSelectData })
</script>

<style lang="scss" scoped>
.data-edit {
  height: 100%;
  margin: 0 var(--ycy-gap-base);
  padding: var(--ycy-gap-base);
  border-radius: var(--el-border-radius-base);
  background-color: var(--el-fill-color-blank);

}
</style>